import { useDrop } from "react-dnd";
import { getComponentById, useComponentStore } from "../stores/components";
import { useComponentConfigStore } from "../stores/component-config";

export interface ItemType {
  type: string;
  dragType: "move" | "add";
  id: string;
}

export function useMaterialDrop(accept: string[], id: string) {
  const { addComponent, deleteComponent } = useComponentStore();
  const { componentConfigs } = useComponentConfigStore();

  const [{ canDrop }, drop] = useDrop(() => ({
    accept,
    drop: (item: ItemType, monitor) => {  
      // 能放置组件的容器组件有多个，有时候可能会触发两个容器组件的 drop 事件
      // 所以这里需要判断一下是否已经放置过组件了，省的同一个组件放置多次
      const didDrop = monitor.didDrop();
      if (didDrop) return;
      if (item.dragType === "move") {
        const { components } = useComponentStore.getState(); // 获取最新的 components
        const component = getComponentById(item.id, components);
        if (component) {
          deleteComponent(item.id);
          addComponent(component, id);
        }
      } else {
        const config = componentConfigs[item.type];
        addComponent(
          {
            id: new Date().getTime().toString(),
            name: item.type,
            props: config.defaultProps,
            desc: config.desc,
            styles: {},
          },
          id
        );
      }
    },
    collect: (monitor) => ({
      canDrop: monitor.canDrop(),
    }),
  }));

  return {
    canDrop,
    drop,
  };
}
